package com.lcz.util;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class FirstFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化开始");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器开始");
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        request.setCharacterEncoding("utf-8");

        //防止用户在未登录的情况下访问资源
        String requestURI = request.getRequestURI();//获得请求地址
        System.out.println("requestURI="+requestURI);
        Object username = request.getSession().getAttribute("username");

        if(requestURI.endsWith("success.jsp") && username==null){
            response.sendRedirect("login.jsp");
        }

        //调取下一个过滤器,或者Servlet
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("结束");

    }

    @Override
    public void destroy() {
        System.out.println("销毁");

    }
}
